package com.leyou.page.service.impl;

import com.leyou.item.pojo.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecificationClient;
import com.leyou.page.service.PageService;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;

    //模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    private final Logger log = LoggerFactory.getLogger(PageServiceImpl.class);

    @Override
    public Map<String, Object> loadModel(Long id) {

        Map<String, Object> model = new HashMap<>();

        Spu spu = goodsClient.querySpuById(id);
        List<Sku> skus = spu.getSkus();
        SpuDetail spuDetail = spu.getSpuDetail();
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        List<Category> categoryList = categoryClient.queryCategoryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        List<SpecGroup> specs = specificationClient.queryListByCid(spu.getCid3());

        //model.put("spu", spu);//不需要spu这么多数据
        model.put("title", spu.getTitle());
        model.put("subTitle", spu.getSubTitle());
        model.put("categories", categoryList);
        model.put("brand", brand);

        model.put("detail", spuDetail);
        model.put("skus", skus);
        model.put("specs", specs);

        return model;
    }

    public void createHtml(Long spuId) {
        //上下文
        Context context = new Context();
        context.setVariables(loadModel(spuId));
        //输出流D:\JAVA全套资料\资料\thymeleaf
        File file = new File("D:\\JAVA全套资料\\资料\\thymeleaf", spuId + "item.html");
        if (file.exists()) {  //存在先删除
            file.delete();
        }
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
            //输出hml
            templateEngine.process("item", context, writer);

        } catch (Exception e) {
            //异常日志
            log.error("静态页生成异常", e);
        }
    }

    @Override
    public void deleteHtml(Long spuId) {
        //输出流D:\JAVA全套资料\资料\thymeleaf
        File file = new File("D:\\JAVA全套资料\\资料\\thymeleaf", spuId + "item.html");
        if (file.exists()) {  //存在删除
            file.delete();
        }
    }


}
